package com.okex.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.okex.demo.model.Account;
import com.okex.demo.model.OrderInfo;
import com.okex.demo.model.PositionInfo;
import com.okex.demo.model.TickerInfo;
import com.okex.demo.service.AccountService;
import com.okex.demo.service.OkexApiService;
import com.okex.demo.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * OKX控制器
 */
@Slf4j
@Controller
public class OkexController {

    @Autowired
    private OkexApiService okexApiService;
    
    @Autowired
    private AccountService accountService;
    
    @Autowired
    private OrderService orderService;
    
    @Value("${okex.default.inst-id:BTC-USDT}")
    private String defaultInstId;

    /**
     * 首页
     */
    @GetMapping("/")
    public String showIndexView(Model model) {
        model.addAttribute("defaultInstId", defaultInstId);
        model.addAttribute("accounts", accountService.findAllActive());
        return "index";
    }
    
    /**
     * 持仓页面
     */
    @GetMapping("/positions")
    public String showPositionsView(Model model) {
        model.addAttribute("accounts", accountService.findAllActive());
        return "positions";
    }
    
    /**
     * 行情页面
     */
    @GetMapping("/ticker")
    public String showTickerView(@RequestParam(required = false) String instId, Model model) {
        if (instId == null || instId.isEmpty()) {
            // 尝试从账户列表中获取第一个产品ID
            List<Account> accounts = accountService.findAllActive();
            if (!accounts.isEmpty()) {
                instId = accounts.get(0).getInstId();
            } else {
            instId = defaultInstId;
            }
        }
        model.addAttribute("instId", instId);
        model.addAttribute("accounts", accountService.findAllActive());
        model.addAttribute("pageDescription", "显示产品管理表中已配置产品的详细行情信息，支持下单交易");
        return "ticker";
    }
    
    /**
     * 所有行情页面
     */
    @GetMapping("/all-markets")
    public String showAllMarketsView(Model model) {
        model.addAttribute("accounts", accountService.findAllActive());
        model.addAttribute("pageDescription", "显示OKX交易所所有产品行情，不限于已配置产品");
        return "all-markets";
    }
    
    /**
     * 获取持仓信息API
     */
    @GetMapping("/api/positions")
    @ResponseBody
    public List<PositionInfo> getPositions() {
        return okexApiService.getPositions();
    }
    
    /**
     * 获取行情信息API
     */
    @GetMapping("/api/ticker")
    @ResponseBody
    public TickerInfo getTicker(@RequestParam(required = false) String instId) {
        return okexApiService.getTicker(instId);
    }

    /**
     * 获取所有产品行情信息API
     * @param instType 产品类型，如 SPOT(币币), SWAP(永续合约), FUTURES(交割合约), OPTION(期权)
     * @param uly 标的指数，适用于交割/永续/期权，如 BTC-USD
     * @param instFamily 交易品种，适用于交割/永续/期权，如 BTC-USD
     * @return 产品行情信息列表
     */
    @GetMapping("/api/tickers")
    @ResponseBody
    public List<TickerInfo> getTickersList(
            @RequestParam String instType,
            @RequestParam(required = false) String uly,
            @RequestParam(required = false) String instFamily) {
        return okexApiService.getTickersList(instType, uly, instFamily);
    }
    
    /**
     * 获取账户API
     */
    @GetMapping("/api/accounts")
    @ResponseBody
    public List<Account> getAccounts() {
        return accountService.findAllActive();
    }
    
    /**
     * 一键平仓API
     */
    @PostMapping("/api/close-positions")
    @ResponseBody
    public ResponseEntity<JSONObject> closePosition(
            @RequestParam String instId,
            @RequestParam String posSide,
            @RequestParam String mgnMode) {
        JSONObject result = okexApiService.closePosition(instId, posSide, mgnMode);
        return ResponseEntity.ok(result);
    }

    /**
     * 订单记录页面
     */
    @GetMapping("/orders")
    public String ordersPage(Model model) {
        // 获取当天的订单记录
        List<OrderInfo> orders = orderService.findTodayOrders();
        model.addAttribute("orders", orders);
        
        // 获取所有产品账户信息，用于下拉选择
        List<Account> accounts = accountService.findAllWithInstId();
        model.addAttribute("accounts", accounts);
        
        return "orders";
    }
} 